/**
 * PostController
 * 
 * @description :: Server-side logic for managing Posts
 * @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers
 */

module.exports = {
	
	list : function(req, res) {
		Post.find()
		.sort('updatedAt DESC')
		.populate('comments')
		.populate('attachments')
		.populate('owner')
		.then(function findCB(result) {
			User.find()
			.then(function findOneCB(users){
				for (var i = 0; i < result.length; i++) {
					var comments = result[i].comments;
					for (var j = 0; j < comments.length; j++) {
						var cmmt = comments[j];
						comments[j].owner = CommonService.getObjectFormArray(users, comments[j].owner, 'userid');
					}
				}
				return res.view('mobile/content/post-list', {
					posts : result,
				});
			});
		}).catch(function(err){
			sails.log.error(err);
			return res.serverError(err);
		});
	},
	
	addLikes : function(req, res){
		var pkid = req.param("pkid");
		Post.findOne(pkid)
		.then(function findCB(result) {
			var likes = result.likes;
			Post.update(pkid,{
				'likes' : (likes+1)
			}).then(function findCB(result) {
				return res.send({success : true});
			});
		}).catch(function(err){
			return res.send({
				success : false,
				error : err
			});
		});
	},
	
	get : function(req, res){
		var method = req.param("method");
		if(method == 'update' || method == 'detail'){
			var pkid = req.param("pkid");
			Post.findOne(pkid)
			.populate('comments')
			.then(function findCB(result) {
				if(method == 'detail'){
					resview = 'mobile/content/post-detail';
					
				}else if(method == 'update'){
					//resview = 'mobile/forms/form-update';
				
				}
				return res.view(resview, {
					post : result,
				});
			}).catch(function(err){
				sails.log.error(err);
				return res.serverError(err);
			});
		}else{
			return res.view('mobile/content/post-create', {});
		}
	}
		
};

